import { onUnmounted, type App } from "vue";

export default{
    install(app:App){
        app.directive('lazy',{
            mounted(el,binding){
                const ImgObserver = new IntersectionObserver(function(images){
                        if(images[0].isIntersecting){
                            const img = new Image();

                            img.onload = function(){
                                el.src=binding.value;

                                el.classList.add('loaded')
                            }

                            img.src=binding.value

                            ImgObserver.unobserve(el);
                        }
                }) 

                ImgObserver.observe(el);
                el._observer = ImgObserver; 

            },
            unmounted(el) {
                if (el._observer) {
                el._observer.disconnect(); // 彻底销毁观察器，防止内存泄漏
                }
            }
        }

    )
    }
}